<?php
/**
 * // +----------------------------------------------------------------------
 * //            -------------------------
 * //           /   / ------------------\  \
 * //                                          \  \
 * //                                           /  /
 * //          /  /  ------------------- /  /
 * //        /  /  ----------------------
 * //      /  /
 * //      \  \
 * //        \  \  ------------------ /  /
 * //          \  \--------------------/
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2016 Sage  All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Author: Sage
 * // +----------------------------------------------------------------------
 *
 */

/**
 * Created by PhpStorm.
 * User: Sage
 * Date: 2017/12/7
 * Time: 15:35
 */
namespace KysbsUtils\Service;
use KysbsUtils\Config;

/**
 * 请求服务
 * Class RequestService
 * @package KysbsUtils\Service
 */
class RequestService {
    static $dataSource=false;
    static $dataParse=false;
    static $devReferer=Config::DEV_REFERER;
    static $formatSeparator=':';

    /**
     * 获取数据
     * @param bool $key，必传
     *
     * @return array|bool|mixed|string
     */
    function getData($key=false) {
        //解析数据
        $data = $this->parseSourceData();
        //取数据
        if(is_string($key)){
            //单个key
            $return= current($this->getSingleData($key));
        }elseif(is_array($key)){
            //批量获取值
            $return=[];
            foreach($key as $sub){
                $return=array_merge($return,$this->getSingleData($sub));
            }
        }else{
            $return=$data;
        }

        return $return;
    }

    /**
     * 解析源数据
     * @return array|bool|mixed
     */
    function parseSourceData(){
        $data = self::$dataParse;
        if ($data === false) {
            if ($this->isFromData()){
                //从data解析取数据
                $source = $this->getSourceData();
                $source=base64_decode($source);
                //处理特殊字符
                $source=preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
                    '|\xED[\xA0-\xBF][\x80-\xBF]/S','?', $source );
                $data= json_decode($source , true);
            }else{
                //直接获取post方式
                $data=$_POST;
            }
            self::$dataParse=$data ;
        }
        if(empty($data))
            return [];
        return $data;
    }

    /**
     * 获取单个数据
     * @param $key
     *
     * @return array
     */
    function getSingleData($key){
        $data=$this->parseSourceData();
        $key_arr=explode(self::$formatSeparator,$key);
        $key=$key_arr[0];
        $value=null;
        if(array_key_exists($key,$data)){
            $value=$data[$key];
        }
        if(!empty($key_arr[1])){
            switch($key_arr[1]){
                case 'int':
                    $value=(int)$value;
                    break;
                case 'float':
                    $value=(float)$value;
                    break;
                case 'string':
                    $value=(string)$value;
                    break;
                case 'array':
                    $value=(array)$this->tryToJsonArray($value);
                    break;
                case 'bool':
                    $value=(bool)$value;
                    break;
                default:
                    $value=$this->tryToJsonArray($value);
                    break;
            }
        }
        return [$key=>$value];
    }

    /**
     * 获取原数据
     * @return bool,字符串
     */
    function getSourceData(){
        if(self::$dataSource===false){
            if(array_key_exists('data',$_POST))
                self::$dataSource=$_POST['data'];
            else
                self::$dataSource='';
        }
        return self::$dataSource;
    }

    /**
     * 是否来自data key获取
     * @return bool
     */
    function isFromData(){
        if(array_key_exists('HTTP_REFERER',$_SERVER) && $_SERVER['HTTP_REFERER']==self::$devReferer)
            //从post取
            return false;
        //默认从data取
        return true;
    }

    /**
     * 获取请求源
     * @return string
     */
    function getOrigin(){
        return isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
    }

    /**
     * 获取当前请求的host地址
     * @return mixed
     */
    function getHost(){
        return $_SERVER['HTTP_HOST'];
    }

    /**
     * 尝试转换为json数组
     * @param $data
     *
     * @return mixed
     */
    function tryToJsonArray($data){
        if(empty(json_decode($data,true)) || json_last_error() != JSON_ERROR_NONE){
            return $data;
        }
        return json_decode($data,true,512,JSON_BIGINT_AS_STRING);
    }
}